package com.ostms.adv.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.ostms.adv.BuildConfig;
import com.ostms.adv.R;
import com.ostms.adv.model.AdvRequestModle;
import com.ostms.adv.play.PayPlayManager;
import com.ostms.adv.service.MainBackService;
import com.ostms.adv.utils.CommonUtils;
import com.ostms.adv.utils.HttpTools;
import com.ostms.adv.utils.LOG;
import com.ostms.adv.utils.Tools;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.FormBody;

public class FaceDetectActivity extends BaseActivity {
    private static final String TAG = FaceDetectActivity.class.getSimpleName();
    private String pathAosen = Environment.getExternalStorageDirectory().getPath() + "/aosen";
    private static final int CHECKSERVERCONNECTSUCCESS = 2;
    private static final int REQUESTDEFAULTADVSUCCESS = 7;
    private static final int REQUESTDEFAULTADVFAILURE = 8;
    private static final int REQUESTDEFAULTADVFAILUREEMPTY = 9;
    private static final int COMADVSTOP = 10;
    private static final String PARAMS_STORE_ID = "store_id";
    private static final String PARAMS_AUTHINFO = "authinfo";
    private static final String PARAMS_OUT_TRADE_NO = "out_trade_no";
    private static final String PARAMS_TOTAL_FEE = "total_fee";
    private static final String PARAMS_MCH_ID = "mch_id";
    private static final String PARAMS_FACE_AUTHTYPE = "face_authtype";
    private static final String PARAMS_APPID = "appid";
    public static final String RETURN_CODE = "return_code";
    public static final String RETURN_MSG = "return_msg";
    private static final String PARAMS_TELEPHONE = "telephone";
    private static final String PARAMS_MCH_NAME = "mch_name";
    private LinearLayout group1;
    private LinearLayout group2;
    private ImageView group1_img_top;
    private ImageView topImg;
    private TextureView middleVideo;
    private LinearLayout group_baidu_image;
    private ImageView group_baidu_image_top;
    private LinearLayout group_baidu_video;
    private TextureView group_baidu_video_video;
    private PayPlayManager player;
    private Context context;
    private HttpTools httpTools;
    private Intent intentMainService;
    private ImageLoader imageLoader;

    private final static int RC_PERMISSION = 10;
    private StringBuilder keycodeMoney =new StringBuilder();
    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == CHECKSERVERCONNECTSUCCESS) {
                Tools.setNetTime();
                requestDefaultAdv();
            } else if (msg.what == REQUESTDEFAULTADVSUCCESS) {//缓存默认广告
                AdvRequestModle advRequestModle = (AdvRequestModle) msg.obj;
                Gson gson = new Gson();
                String json = gson.toJson(advRequestModle);
                Tools.setProperties(context, CommonUtils.ADV_DEFAULTADV, json);
            } else if (msg.what == REQUESTDEFAULTADVFAILUREEMPTY) {
                Tools.setProperties(context, CommonUtils.ADV_DEFAULTADV, "");
            } else if (msg.what == REQUESTDEFAULTADVFAILURE) {
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        String versionName = Tools.getAppVersion(context);
        LOG.i(TAG, "onCreate 启动:当前版本号：" + versionName);
        LOG.i(TAG, "BuildConfig.TARGET_CUSTOMER = " + BuildConfig.TARGET_CUSTOMER);
        File f = new File(pathAosen);
        if (!f.exists()) {
            f.mkdirs();
        }
        //隐藏虚拟按键
        hideBottomUIMenu();
        hintKeyBoard();
        //界面布局
        setContentView(R.layout.play_adv);
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
        //初始化控件
        initView();
    }


    public void initData() {
        httpTools = new HttpTools(context);
        if (null == player) {
            player = new PayPlayManager(context, httpTools, imageLoader, mHandler);
            player.registerAllAdvertiseView(new View[]{group1, group2, group_baidu_video, group_baidu_image});
            player.registerOstmsGroup1View(group1, group1_img_top);
            player.registerOstmsGroup2View(group2, topImg, middleVideo);
            player.registerBaiduVideoView(group_baidu_video);
            //注册底部view
            player.registerBottomView(ll_bottom);
        }

        //组合广告
        addListenerToTexture(middleVideo, new TextureListener() {
            @Override
            public void onAvailable(Surface surface) {
                player.setGroup2Surface(surface);
            }
        });
        //单视频广告
        addListenerToTexture(group_baidu_video_video, new TextureListener() {
            @Override
            public void onAvailable(Surface surface) {
                player.setBaiduVideoSurface(surface);
            }
        });
        player.standbyPlay();
        //启动主服务
        if (!Tools.isServiceRunning(context, "com.ostms.adv.service.MainBackService")) {
            intentMainService = new Intent(context, MainBackService.class);
            startService(intentMainService);
        }
        //判断设备是否连接网络
        checkServerConnect();
    }


    private void requestDefaultAdv() {
        String path = CommonUtils.DEFAULT_ADV;
        //String equipmentCode = OstmsApp.getEquipmentCode();
        String equipmentCode =  Tools.initEquipmentCode();
        FormBody.Builder builder = new FormBody.Builder();//创建表单请求体
        builder.add("equipmentCode", equipmentCode);
        httpTools.sendPostdata(path, builder, new HttpTools.HttpLisenner() {
            @Override
            public void onFailure(Call call, IOException e) {
                LOG.i(TAG, "requestDefaultAdv 失败:" + e.toString());
                mHandler.sendEmptyMessage(REQUESTDEFAULTADVFAILURE);
            }

            @Override
            public void onResponse(Call call, String result) {
                LOG.i(TAG, "requestDefaultAdv 成功:" + result);
                try {
                    if (null != result && result.length() > 0) {
                        Gson gson = new Gson();
                        AdvRequestModle advRequestModle = gson.fromJson(result, AdvRequestModle.class);
                        if (null != advRequestModle.getAds() && advRequestModle.getAds().size() > 0) {
                            Message msg = Message.obtain();
                            msg.what = REQUESTDEFAULTADVSUCCESS;
                            msg.obj = advRequestModle;
                            mHandler.sendMessage(msg);
                        } else {
                            mHandler.sendEmptyMessage(REQUESTDEFAULTADVFAILURE);
                        }
                    } else {
                        mHandler.sendEmptyMessage(REQUESTDEFAULTADVFAILUREEMPTY);
                    }
                } catch (Exception e) {
                    mHandler.sendEmptyMessage(REQUESTDEFAULTADVFAILURE);
                }
            }
        });
    }

    public void checkServerConnect() {
        String path = CommonUtils.APPCOLLECT;
        FormBody.Builder builder = new FormBody.Builder();
        httpTools.sendPostdata(path, builder, new HttpTools.HttpLisenner() {
            @Override
            public void onFailure(Call call, IOException e) {
                LOG.i(TAG, "服务器连接不通10S后继续监测:" + e);
                long minute = 1000 * 10;
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        checkServerConnect();
                    }
                }, minute);
            }

            @Override
            public void onResponse(Call call, String result) {
                if ("1".equals(result)) {
                    mHandler.sendEmptyMessage(CHECKSERVERCONNECTSUCCESS);
                } else {
                    LOG.i(TAG, "服务器连接不通10S后继续监测");
                    long minute = 1000 * 10;
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            checkServerConnect();
                        }
                    }, minute);
                }

            }
        });
    }

    private void defaultView() {
        group_baidu_image.setVisibility(View.GONE);
        group_baidu_video.setVisibility(View.GONE);
        group2.setVisibility(View.GONE);
        group1.setVisibility(View.VISIBLE);
        changeBottomUIMenu(this);
        if(BuildConfig.TARGET_CUSTOMER.contains("yibei")){
            ll_bottom.setVisibility(View.GONE);
        }
    }

    private void addListenerToTexture(TextureView texture, final TextureListener listener) {
        texture.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                listener.onAvailable(new Surface(surface));
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {

            }
        });

    }

    private interface TextureListener {
        void onAvailable(Surface surface);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        //单图
        group1 = findViewById(R.id.group1);
        group1_img_top = findViewById(R.id.group1_img_top);
        //图+视频
        group2 = findViewById(R.id.group2);
        topImg = findViewById(R.id.topImageView);
        middleVideo = findViewById(R.id.videoview);
        //百度单图
        group_baidu_image = findViewById(R.id.group_baidu_image_view);
        group_baidu_image_top = findViewById(R.id.group_baidu_image_top);
        //百度视频
        group_baidu_video = findViewById(R.id.group_baidu_video_view);
        group_baidu_video_video = findViewById(R.id.group_baidu_video_video);
        //底部图片
        ll_bottom = findViewById(R.id.ll_bottom);
        iv_bottom = findViewById(R.id.iv_bottom);

        /*Button mTestUpdateButton = findViewById(R.id.testUpdate);

        mTestUpdateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String path = Environment.getExternalStorageDirectory().getPath() + "/aosen/app/" + "ostmswx-advRelease-v1.0.5.1.0.5.apk";
                Tools.silentInstall(path, FaceDetectActivity.this);
            }
        });*///测试apk升级
    }


    private LinearLayout ll_bottom;
    private ImageView iv_bottom;

    /**
     * Activity创建或者从后台重新回到前台时被调用
     */
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart is invoke!!!");
    }


    /**
     * Activity创建或者从被覆盖、后台重新回到前台时被调用
     */
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume is invoke!!!");
        defaultView();
        initData();
    }

    /**
     * Activity被覆盖到下面或者锁屏时被调用
     */
    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause is stop!!");
    }

    /**
     * 退出当前Activity或者跳转到新Activity时被调用
     */
    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop is invoke!!!");
        stopAllWork();
    }

    public void stopAllWork() {
        if (null != player) {
            LOG.i(TAG, "player 停止");
            player.closePlay();
            player.standbyStop();
        }
        if (null != mHandler) {
            mHandler.removeCallbacksAndMessages(null);
        }
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        manager.killBackgroundProcesses(getPackageName());
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * 退出当前Activity时被调用,调用之后Activity就结束了
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy is invoke!!!");
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 修改虚拟按键显示状态
     *
     * @param context
     */
    private void changeBottomUIMenu(Activity context) {
        // 修改虚拟按键显示状态
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            View v = context.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        }
        // api19之后需要做别的处理
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            View decorView = context.getWindow().getDecorView();
            //微信支付打包
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(BuildConfig.TARGET_CUSTOMER.contains("yibei")){
            //设备
            if (keyCode == 144) {
                keycodeMoney.append("0");
            } else if (keyCode == 145) {
                keycodeMoney.append("1");
            } else if (keyCode == 146) {
                keycodeMoney.append("2");
            } else if (keyCode == 147) {
                keycodeMoney.append("3");
            } else if (keyCode == 148) {
                keycodeMoney.append("4");
            } else if (keyCode == 149) {
                keycodeMoney.append("5");
            } else if (keyCode == 150) {
                keycodeMoney.append("6");
            } else if (keyCode == 151) {
                keycodeMoney.append("7");
            } else if (keyCode == 152) {
                keycodeMoney.append("8");
            } else if (keyCode == 153) {
                keycodeMoney.append("9");
            } else if (keyCode == 158) {
                keycodeMoney.append(".");
            }else if(keyCode == 160||keyCode == 66){
                Intent mIntent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("keycodeMoney", keycodeMoney.toString());
                setResult(150, mIntent.putExtras(bundle));

                keycodeMoney.delete(0,keycodeMoney.length()+1);
                finish();
                return super.onKeyDown(keyCode, event);
            }

        }else{
            finish();
            return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }
}
